using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Domain;
using Rabbit.Infrastructure.Interface;
using MD5Hash;
using RabbitTeacebillty.API.Read.Application.Command;
using System.Linq;
using Infrastructure;
using RabbitTraceability;

namespace RabbitTeacebillty.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 注册用户请求处理器，包含基本校验，返回ApiResult
    /// </summary>
    public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> _userRepository;
        public RegisterUserCommandHandler(IBaseRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }
        public async Task<ApiResult<int>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            // 基本校验：用户名和密码不能为空
            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Code = ResultCode.BadRequest,
                    Message = "用户名和密码不能为空",
                    Data = 0
                };
            }
            // 用户名唯一性校验
            var exists = _userRepository.GetAll().Any(u => u.UserName == request.UserName);
            if (exists)
            {
                return new ApiResult<int>
                {
                    Success = false,
                    Code = ResultCode.Conflict,
                    Message = "用户名已存在",
                    Data = 0
                };
            }
            // 密码加密
            string passwordHash = request.Password.GetMD5();
            var user = new User
            {
                UserName = request.UserName,
                PasswordHash = passwordHash
            };
            await _userRepository.AddAsync(user);
            return new ApiResult<int>
            {
                Success = true,
                Code = ResultCode.Success,
                Message = "注册成功",
            };
        }
    }
} 